package com.crois.barrier.metrics.facade;

import com.crois.barrier.metrics.api.MetricsBootService;
import com.crois.barrier.metrics.config.MetricsConfig;
import com.crois.barrier.metrics.prometheus.service.PrometheusMetricsBootService;
import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author Hou Ze Yu
 * @description
 * @date 2021/4/20
 */
@Slf4j
public class MetricsTrackerFacade {

    private MetricsBootService metricsBootService =  new PrometheusMetricsBootService();

    private final AtomicBoolean isStarted = new AtomicBoolean(false);

    private MetricsTrackerFacade() {
    }

    /**
     * Get metrics tracker facade of lazy load singleton.
     *
     * @return metrics tracker facade
     */
    public static MetricsTrackerFacade getInstance() {
        return MetricsTrackerFacadeHolder.INSTANCE;
    }

    /**
     * Init for metrics tracker manager.
     *
     * @param metricsConfig metrics config
     */
    public void start(final MetricsConfig metricsConfig) {
        if (this.isStarted.compareAndSet(false, true)) {
            Preconditions.checkNotNull(metricsBootService,
                    "Can not find metrics tracker manager with metrics name : %s in metrics configuration.", metricsConfig.getMetricsName());
            metricsBootService.start(metricsConfig);
        } else {
            log.info("metrics tracker has started !");
        }
    }

    /**
     * Stop.
     */
    public void stop() {
        this.isStarted.compareAndSet(true, false);
        if (null != metricsBootService) {
            metricsBootService.stop();
        }
    }

    /**
     * Check if start or not.
     *
     * @return true is stared, otherwise not.
     */
    public boolean isStarted() {
        return isStarted.get();
    }

    /**
     * Metrics tracker facade holder.
     */
    private static class MetricsTrackerFacadeHolder {
        private static final MetricsTrackerFacade INSTANCE = new MetricsTrackerFacade();
    }
}
